package com.demo.controller;

import com.demo.dao.NewsDao;
import com.demo.dao.VenueDao;
import com.demo.entity.News;
import com.demo.entity.Venue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.stream.IntStream;

import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
class IndexControllerIT {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private NewsDao newsDao;

    @Autowired
    private VenueDao venueDao;

    private final int TOTAL_NEWS = 5;
    private final int TOTAL_VENUES = 3;

    @BeforeEach
    void setUp() {
        // 清空数据库
        newsDao.deleteAll();
        venueDao.deleteAll();

        // 插入测试新闻数据
        IntStream.rangeClosed(1, TOTAL_NEWS).forEach(i -> {
            News news = new News(
                    0,
                    "新闻标题" + i,
                    "这是新闻内容" + i,
                    LocalDateTime.now().minusDays(i)
            );
            newsDao.save(news);
        });

        // 插入测试场馆数据
        IntStream.rangeClosed(1, TOTAL_VENUES).forEach(i -> {
            Venue venue = new Venue(
                    0,
                    "场馆" + i,
                    "这是场馆描述" + i,
                    100 * i,
                    "/images/venue" + i + ".jpg",
                    "地址" + i,
                    "08:00",
                    "18:00"
            );
            venueDao.save(venue);
        });

        assertEquals(TOTAL_NEWS, newsDao.count());
        assertEquals(TOTAL_VENUES, venueDao.count());
    }

    @Test
    void index_ShouldReturnModelWithNewsAndVenues() throws Exception {
        mockMvc.perform(get("/index"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(model().attributeExists("news_list"))
                .andExpect(model().attributeExists("venue_list"))
                .andExpect(content().string(containsString("新闻标题1")))
                .andExpect(content().string(containsString("场馆1")));
    }

    @Test
    public void testAdminIndexPageLoadsCorrectly() throws Exception {
        mockMvc.perform(get("/admin_index"))
                .andExpect(status().isOk())
                .andExpect(view().name("admin/admin_index"));
    }
}
